import Vue from 'vue'
import VueRouter from 'vue-router'
import NProgress from 'nprogress'
import 'nprogress/nprogress.css'

NProgress.configure({
  easing: 'ease', // 动画方式
  speed: 500, // 递增进度条的速度
  showSpinner: false, // 是否显示加载ico
  trickleSpeed: 200, // 自动递增间隔
  minimum: 0.3, // 初始化时的最小百分比
})

Vue.use(VueRouter)

const routes = [
  {
    path:'/',
    redirect: '/user'
  },
  {
    path:'/user',
    name: 'user',
    meta:{
      role:['user','super']
    },
    component: () => import('views/user/home')
  },
  {
    path:'/admin',
    name: 'admin',
    meta:{
      role:['user','super']
    },
    component: () => import('views/admin/home')
  },
  {
    path: '/login',
    name:'login',
    component: () => import('views/login')
  },
  {
    path: '*',
    name: 404,
    component: () => import('views/404')
  }
]
// importComponents(require.context("../views", true, /\.vue$/, "lazy"));
// function importComponents(r) {
//   r.keys().forEach((key) => {
//     routes.push({
//       path: key.substring(key.indexOf('/'), key.lastIndexOf('.')),
//       name: key.substring(key.indexOf('/'), key.lastIndexOf('.')).split('/')[1]
//         .toLowerCase(),
//       component: () => r(key),
//       meta: { requireAuth: false },
//     })
//   });
// }

const router = new VueRouter({
  mode: 'history',
  routes,
  scrollBehavior(to, from, savedPosition) {
    if (savedPosition) {
      return savedPosition
    } else {
      return { x: 0, y: 0 }
    }
  },
})

// 路由拦截器
router.beforeEach((to, from, next) => {
  NProgress.start()
  const isAuthenticated = router.app.$options.store.state.role
  if (!isAuthenticated) {
    if (to.name !== 'login') next({ name: 'login' })
    next()
  } else {
    if(to.meta.role && to.meta.role.includes(isAuthenticated)) {
      next()
    } else if(to.meta.role && !to.meta.role.includes(isAuthenticated)) {
      next({ name: '404' })
    }
    next()
  }
})
router.afterEach(() => {
  NProgress.done()
})

export default router
